var flushPriceMax = 2; // 最大刷新价格次数

// 程序变量
var rdCheck; // 请求随机码
var totalAmount; // 现金支付金额
var cardAmount; // 礼品卡支付金额
var phoneNum;
var httpUrl;

// 刷新价格，使用余额
function useYE(){
    if(payType==2 || payType==3){// 使用余额
		httpUrl = 'http://buy.yhd.com/checkoutV3/payment/sendAccountVerifyCode.do?amount='+totalAmount;
		$.ajax({
			url:httpUrl,
			type:'POST',
			success:function(data){
				if(data.accountSmsSendResult.message == '短信发送成功'){
					phoneNum = data.accountSmsSendResult.data.mobile;
					$(document.body).append('短信发送成功，延时查询验证码...<br />');
					setTimeout(getRdForBuy,timeOut);
				}else{
					$(document.body).append('短信发送失败：'+data.accountSmsSendResult.message);
				}
			}
		});
	}else{
		submitOrder();
	}
}
//刷新购物车
function refreshCartPrice(failFlag){
    httpUrl = 'http://buy.yhd.com/checkoutV3/init/init.do?cart2Checkbox=&operateFlag=&cartSuppress=&returnUrl=';
	$.ajax({
		type : 'GET',
		url : httpUrl,
		dataType : 'json',
		async : false, // 同步等待结果
		success : function(data) {
			if (data.checkoutError == null) { // 价格正确
			    $(document.body).append('价格正确,校验价格类型<br />');
				// 判断类型
				var products = data.productsMap;
				var i = 0;
				while (true) {
					var index = '' + i;
					if (products[index] == undefined) {
					    console.log('Product0 Undefined');
						failFlag = true;
						break;
					}else if (!products[index].gift
							&& products[index].ruleType == 2) {
                        $(document.body).append('是团购价，提交订单<br />');
						rdCheck = data.invoiceDTO.orderRundomString;
						totalAmount = data.paymentList.paymentAccount.cashAmountNeedToPay;//需支付的总金额
						cardAmount = data.paymentList.paymentAccount.useableCardAmount;//礼品卡可用余额
						break;
					}
					i = i + 1;
				}
			}else{
				$(document.body).append(data.checkoutError.msg);
				failFlag = true;
			}
		}
	});
    return failFlag;
}

function flushPrice(){
	$(document.body).append('刷新价格<br />');
	var failFlag = false; // 刷新价格成功
	// 刷新价格
	failFlag = refreshCartPrice(failFlag);
	// 刷新价格失败，再次刷新
	if(failFlag){
		flushPriceMax--;
		if(flushPriceMax > 0){ // 未超过最大次数
			setTimeout(flushPrice, 1667);
		}
		$(document.body).append("刷不到促销价<br />");
		return;
	}
	useYE();
}

function getRdForBuy(){
    //获取CRM验证码
	chrome.extension.sendMessage({greeting:"smsCode",No:phoneNum},function(response){
        $(document.body).append('获取到的验证码：'+response.smsCode);
  		if(response.smsCode!='error'){
  			if(payType==2){
  				usingAccountPay(response.smsCode);
  			}else if(payType==3){
  				usingCardAccountPay(response.smsCode);
  			}
  		}
	});
}

function usingCardAccountPay(code){
	// 使用礼品卡支付逻辑
	if(cardAmount > 0){
		httpUrl = 'http://buy.yhd.com/checkoutV3/payment/savePaybyAccount.do?accountType=card&amount=' + cardAmount + '&vaildCode='+code;
		$.ajax({
			type : 'POST',
			url : httpUrl,
			dataType : 'json',
			async : false, // 同步等待结果
			success : function(data) {
				submitOrder();
			}
		});
	}
}

function usingAccountPay(code){
	// 使用账户余额支付逻辑
	if(totalAmount > 0){
		httpUrl = 'http://buy.yhd.com/checkoutV3/payment/savePaybyAccount.do?accountType=cash&amount='
				+ totalAmount + '&vaildCode='+code;
		$.ajax({
			type : 'POST',
			url : httpUrl,
			dataType : 'json',
			success : function(data) {
				submitOrder();
			}
		});
	}
}

// 提交订单
function submitOrder(){
	$(document.body).append('提交订单<br />'+rdCheck);
	// 提交订单
	httpUrl = 'http://buy.yhd.com/checkoutV3/confirm/confirmOrder.do?orderID=1&rdCheck='
			+ rdCheck + '&rd=' + Math.random() + '&needProductDetail=1';
	$.ajax({
		type : 'POST',
		url : httpUrl,
		dataType : 'json',
		async : false, // 同步等待结果
		success : function(data) {
			if(data.checkoutError == null){ // 提交成功
			    if(payType==1){//扫码
			        goQRcode(data.orderCode);
			        return;
			    }else if(payType==4){//支付宝网页
			        window.location.href="http://my.yhd.com/gateway/select_gateway.do?orderId="+data.orderCode+"&preType=0&gatewayCode=alipay";
			    }else{
				    window.location.href="http://my.yhd.com/order/finishOrder.do?orderCode="+data.orderCode;
			    }
			}else{
				$(document.body).append('提交失败<br />');
				flushPriceMax--;
				if(flushPriceMax > 0){ // 未超过最大次数
					$(document.body).append('正在重试<br />');
					flushPrice();
				}
			}
		}
	});
}
//跳转到二维码

//function goQRcode(code){
//    var ignoreUrl = "http://cashier.yhd.com/order/finishOrder.do?orderCode="+code;
//    $.get(ignoreUrl,function(){null;});
//	var httpUrl = "http://my.yhd.com/order/changePaymentForFinishOrder.do?gatewayCode=alipay&orderId=" + code + "&paySignId=&paySignNo=";
//	jQuery.getJSON(httpUrl,function(data){
//		window.location = data.saomaUrl;
//	});
//}

function goQRcode(code){
	httpUrl = 'http://cashier.yhd.com/order/finishOrder.do?orderCode=' + code;
	jQuery.get(httpUrl,function(data){
		payUrl = $(data).find("#pay_shaoma_div").find("#pay_shaoma_iframe").find("iframe").attr("src");
		window.location = payUrl;
	});
}

//加购物车
function checkAddCart(){
	$(document.body).append('开始加购物车<br />');
    if(flushPriceMax-- <= 0){
        return;
    }
    httpUrl = 'http://cart.yhd.com/cart/opt/add.do?productId=' + productId + '&rd=' + Math.random();
    $.getJSON(httpUrl, function(data){
        if (data.code != '00000000') { // 加购物车失败
            $(document.body).append(data.msg+'<br/>');
            setTimeout(checkAddCart, 200);
        }else{
            $(document.body).append('加车成功<br />');
            flushPrice();
        }
    });
}

//Main方法
(function(){
    flushPrice();
    submitOrder();
})();